package com.example.communitysystem.controller;

import com.example.communitysystem.dto.AccessTokenDTO;
import com.example.communitysystem.dto.GithubUser;
import com.example.communitysystem.mapper.UserMapper;
import com.example.communitysystem.model.User;
import com.example.communitysystem.provider.GithubProvider;
import com.example.communitysystem.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.UUID;

@Controller
public class AuthorizeController {

    private GithubProvider githubProvider;

    private UserService userService;

    @Value("${gitee.client.id}")
    private String clientId;
    @Value("${gitee.client.secret}")
    private String clientSecret;
    @Value("${gitee.redirect.uri}")
    private String redirectUri;
    @Value("${gitee.grant.type}")
    private String grantType;

    @Autowired
    private UserMapper userMapper;

    //登录获取码云用户信息方法
    @RequestMapping ("/callback")
    public String callback(@RequestParam(name = "code")String code,
                           @RequestParam(name = "state", defaultValue = "state")String state,
                           HttpServletRequest request, HttpServletResponse response) throws IOException {
        //用java模拟http请求:okhttp
        AccessTokenDTO accessTokenDTO = new AccessTokenDTO();
        //System.out.println("code: "+code);
        accessTokenDTO.setCode(code);
        accessTokenDTO.setClient_id(clientId);
        accessTokenDTO.setClient_secret(clientSecret);
        accessTokenDTO.setState(state);
        accessTokenDTO.setRedirect_uri("http://localhost:8081/callback");
        accessTokenDTO.setGrant_type(grantType);
        //通过GithubProvider类获取github的accesstoken
        String accessToken = githubProvider.getAccessToken(accessTokenDTO);
        //System.out.println("accessToken: "+accessToken);
        GithubUser githubUser = githubProvider.getUser(accessToken);
        //打印用户信息
        /*if(githubUser != null){
            System.out.println("githubUser: "+githubUser);
        }*/

        if(githubUser != null){
            //登录成功
            User user = new User();
            user.setName(githubUser.getName());
            user.setLoginName(githubUser.getLogin());
            user.setAccountId(String.valueOf(githubUser.getId()));
            String token = UUID.randomUUID().toString();
            user.setToken(token);
            user.setAvatarUrl(githubUser.getAvatar_url());
            user.setGmtCreate(System.currentTimeMillis());
            user.setGmtModified(user.getGmtCreate());
            //向数据库添加用户
            //先判断用户的用户名是否存在
            //用户存在则更新用户信息，用户不存在则插入用户
            userService.createOrUpdate(user);

            //添加cookie，返回给用户端
            response.addCookie(new Cookie("token",token));
            return "redirect:/";
        }else{
            //登录失败
            return "redirect:/";
        }

    }

    //退出登录方法
    @GetMapping("/logout")
    public String logout(HttpServletRequest request, HttpServletResponse response){
        request.getSession().removeAttribute("user");
        Cookie cookie = new Cookie("token", null);
        cookie.setMaxAge(0);
        response.addCookie(cookie);
        return "redirect:/";
    }
    //测试方法
    @RequestMapping("/test")
    @ResponseBody
    public void test(){
        User user = null;// = new User();
        /*user.setName("lipei");
        user.setAccountId("li123");
        user.setToken("abc123");
        System.out.println(user);
        int i = userMapper.insertUser(user);
        if(i > 0){
            return "添加成功！";
        }else{
            return "添加失败！";
        }*/
        user = userMapper.findByToken("65f0802c-dfe3-4113-9406-d4d90460e01a");
        if(user != null){
            System.out.println("user不为空: "+user);
        }else{
            System.out.println(user);
        }
    }

    @Autowired
    public void setGithubProvider(GithubProvider githubProvider) {
        this.githubProvider = githubProvider;
    }

    @Autowired
    public void setUserService(UserService userService) {
        this.userService = userService;
    }
}
